<?php

namespace control;
/*
*结账
*/


use DateInterval;
use DatePeriod;
use DateTime;

class terminalTransferClass extends adIndexClass
{
    private const page = 'terminalTransfer';
    private const title = '期末结转';
    private const table = 'period_end_setting';
    private const tableMx = 'period_end_setting_detail';
    private string $pass_ico = root . 'img/control/pass.svg';
    private string $no_pass_ico = root . 'img/control/no_pass.svg';
    private string $problem_ico = root . 'img/control/exclamation.svg';
    private const ruleOption = ['余额'];


    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow = '结账'): string
    {
        $html = hidden(array('name' => 'type', 'value' => $this->get('type'))) .
            hidden(array('name' => 'month', 'value' => $this->get('month'))) .
            hidden(array('name' => 'stage', 'value' => $this->get('stage') ?: 'first'));
        //生成查询表单
        return $this->search($html, 'menu', 'no');
    }

    /*列表-查询条件*/
    public function home($workFlow = '结账')
    {
        return $this->homeFun($this->homeForm($workFlow));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        $html = $this->homeContent();
        $html .= $this->style() . $this->js();
        //控件
        //返回
        $json['html'] = "<form name='listForm'>" . space . $html . "</form>" . space . clear;
        return json_encode($json, 320);
    }


    public function homeContent()
    {
        $company = query('company', "coid = '" . self::$coid . "'");
        $start   = new \DateTime($company['startDate'] . '-01');
        $end     = new \DateTime($this->date);
        //$end->modify('+1 month');
        $interval = DateInterval::createFromDateString('1 month');
        $period   = new DatePeriod($start, $interval, $end);
        $preYear  = '';//上一年
        $content  = '';
        $months   = [];
        foreach ($period as $k => $dt) {
            $months[] = $dt->format("Y-m");
        }
        $months = array_reverse($months);
        foreach ($months as $k => $val) {
            $monthText = date("m月", strtotime($val . '-01'));//当前月份
            $year      = date("Y", strtotime($val . '-01'));//当前年份
            $month     = date("Y-m", strtotime($val . '-01'));//当前月份
            //判断是否已结转了损益
            $borderClass     = 'yellow-border';
            $backgroundClass = 'yellow';
            //判断是否已结转了损益
            if (self::isChecked($month)) {
                $borderClass     = 'gray-border';
                $backgroundClass = 'gray';
            }
            if (empty($preYear) || $preYear != $year) {
                $content .= <<<eof
            <div class="period-content-year">
                <div><p><span class="year-font">{$year}年</span></p></div>
                <div class="row-item-ul">
eof;
            }
            $content .= <<<eof
                <div class="month-item row-item $borderClass" onclick="newIframe('结账','{$this->root}control/adIndex.html?cla=terminalTransfer&fun=setting&month={$month}')">
                    <div class="row-item-top $backgroundClass"></div>
                    <div class="row-item-bottom">$monthText</div>
                </div>
eof;
            if (isset($months[$k + 1]) && $year != date('Y', strtotime($months[$k + 1] . '-01'))) {
                $content .= <<<eof
                 </div>
                </div>
eof;
            }
            $preYear = $year;
        }
        return <<<efo
<div style="padding: 0 10px">
    <div class="period-button">
        <span><div class="dot yellow"></div>&nbsp;未结转损益</span>&emsp;&emsp;<span><div class="dot gray"></div>&nbsp;已结转损益</span>
    </div>
    <div class="period-content">
        $content
    </div>
</div>
efo;
    }

    /**
     * js
     * @return string
     */
    private function js(): string
    {
        return <<<eof
<script>

</script>
eof;

    }

    /*客户列表-查询条件*/
    public function setting(): string
    {
        $month   = $this->get('month');
        $data    = [
            "id"   => $month,
            "menu" => [
                "system" => "系统模板",
                "custom" => "自定义模板",
            ]
        ];
        $edit    = 1;
        $disable = '';
        //判断是否已结转了损益
        if (self::isChecked($month)) {
            $edit    = 0;
            $disable = 'disabled';
        }
        //系统模板
        $all = find(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "' and isDel = 0 order by list asc"));
        $li  = '';
        foreach ($all['array'] as $array) {

            $voucher = query('voucher', "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and sourceId = '$array[id]' and source = '期末结转'");
            if ($voucher['id']) {
                $lineDisable = 'disabled';
                $money       = round(self::centToYuan($voucher['money']), 2);
                $btn         = <<<eof
<span class="spanButton" onclick="layer('terminalTransfer','voucherPage',{id:'{$voucher['id']}'})">查看凭证</span>
eof;
            } else {
                $lineDisable = $disable;
                $money       = '&nbsp;';
                $btn         = $edit ? "<span class=\"spanButton\" onclick=\"layer('terminalTransfer','voucherPage',{method:'endPeriod', month:'{$month}', sourceId:'{$array['id']}'})\">生成凭证</span>" :
                    "<span class=\"spanButton disable-button\">生成凭证</span>";
            }
            $box     = "<label class='checkbox'><input name='listId[]' type='checkbox' value='{$array['id']}' " . $lineDisable . "><span " . $lineDisable . "></span></label>";
            $content = <<<eof
<p>
    <img class="set-ico" onclick="layer('terminalTransfer','settingSysPage',{id:'{$array['id']}', month:'{$month}'})" alt="" src="{$this->root}img/control/setting.svg">
    {$box}
</p>
{$btn}
eof;
            $li      .= <<<eof
            <li id="{$array['id']}">
             <div class="tag-contain">
                   <div class="tag-contain-title">
                         <span class="tag-contain-title-text">{$array['name']}</span>
                   </div>
                   <div class="tag-contain-body">
                         <ul class="tag-contain-ul">
                             <li>$money</li>
                         </ul>
                   </div>
                   <div class="tag-contain-foot"></div>
                   <div class="tag-edit-content">
                         $content
                   </div>
             </div>
            </li>
eof;
        }
        $button[] = [
            "name"  => '测算金额',
            "type"  => "点击事件",
            "fun"   => "calculateAamount()",
            "style" => "li-btn-blue-bg",
        ];
        $hidden   = hidden(['name' => 'month', 'value' => $month]);
        //生成表单
        $data['button'] = $this->tableShowButton($button) . "
        <label title='全选' class='listCheckbox'>
            <input type='checkbox' form='terminal' name='listId' onchange='checkAllNew(this)' />
            <span></span>
        </label>";
        $data['html']   = "<form name='terminal'><div class='setting-content'>
                                    <ul class='tag-list-ul'>
                                        $li
                                    </ul>
                                    $hidden
                                </div>
                            </form>";
        return $this->tab($data) . $this->settingStyle() . $this->settingJs();
    }

    /**
     *
     * @return string
     */
    private function settingJs(): string
    {
        return <<<eof
<script>
function calculateAamount(){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=calculateAamount', $("form[name='terminal']").serialize(),function(resp) {
         if (resp.warn === 2){
            if(resp.data){
                for (var i = 0; i < resp.data.length; i++) {
                    $("#"+resp.data[i].id).find('.tag-contain-ul').html(resp.data[i].html)
                }
            }
         }else{
             msg(resp.warn);
         }
        },'json');
    }
    /***全选***/
function checkAllNew(obj) {
    var formName = $(obj).attr("form");
    var checkName = $(obj).attr("name");
    var form = $("[name='" + formName + "']");
    var bool = $(obj).prop("checked");

    let isFixed = false;
    form.children().each(function () {
        if ($(this).hasClass('fixed-thead')) {
            isFixed = true;
        }
    });

    if (isFixed) {
        form.find(".fixed-thead-body [name='" + checkName + "\\[\\]']").not("[disabled]").prop('checked', bool);
    } else {
        form.find("[name='" + checkName + "\\[\\]']").not("[disabled]").prop('checked', bool);
    }
}
</script>
eof;

    }

    public function voucherPage()
    {

        $voucherClass = new voucherEditClass();
        $param        = [
            'method'    => $this->post('method'),
            'id'        => $this->post('id') ?: suiji(),
            'month'     => $this->post('month'),
            'settingId' => $this->post('settingId'),
            'sourceId'  => $this->post('sourceId'),
        ];
        $html         = $voucherClass->voucherHtml($param);
        $html         .= $voucherClass->css() . "<style>[name='voucherForm']{height: 660px;}</style>";
        $html         .= $voucherClass->js();
        //返回
        return $this->layer(array("title" => "编辑", "height" => 700, "width" => 1200, "html" => $html, "button" => false, "remove" => "carryoverCheck('" . $this->post('sourceId') . "')"));
    }

    public function settingSysPage()
    {
        $id    = $this->post('id');
        $month = $this->post('month');
        $info  = query(self::table, "id = '$id'");
        $title = $info['name'];
        $width = 900;
        if ($info['name'] == '计提工资') {
            $tr[] = ['摘要', '会计科目', '方向'];
            $all  = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $k => $array) {
                $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                $tr[]    = [
                    $summary,
                    subjectClass::getShortName($array['subjectId']),
                    $array['direction']
                ];
            }
            $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'showSort' => true));
            $mode  = "<label class='radioLabel'>&nbsp;<input name='para' type='radio' value='手动生成' checked>&nbsp;手动生成</label>";
            $space = space;
            //生成表单
            $html   = <<<eof
<form name="templateForm">
    <div class="layerList">
        <p class="nobottom-title">1、计提方式</p>
        <div class="flex-box">
            $mode
        </div>
        {$space}
        <p class="nobottom-title">2、凭证模板</p>
        <div>
            $table
        </div>
        <input type="hidden" name="id" value="$id">
    </div>
</form>
eof;
            $height = 300;
        } elseif ($info['name'] == '计提折旧') {
            $tr[] = ['摘要', '会计科目', '方向', '资产属性', '取数规则'];
            $all  = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $k => $array) {
                $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                $tr[]    = [
                    $summary,
                    subjectClass::getShortName($array['subjectId']),
                    $array['direction'],
                    '固定资产',
                    zishu($array['rule'], 20),
                ];
            }
            $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'showSort' => true));
            $mode  = "<label class='radioLabel'>&nbsp;<input name='para' type='radio' value='没有固定资产记录' disabled>&nbsp;没有固定资产记录</label>
<label class='radioLabel'>&nbsp;<input name='para' type='radio' value='有固定资产记录' checked>&nbsp;有固定资产记录</label>";
            $space = space;
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <p class="nobottom-title">1、计提方式</p>
                <div class="flex-box">
                    $mode
                </div>
                {$space}
                <p class="nobottom-title">2、凭证模板</p>
                <div>
                    $table
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        eof;
            $height = 300;
        } elseif ($info['name'] == '摊销无形资产') {
            $tr[] = ['摘要', '会计科目', '方向', '资产属性', '取数规则'];
            $all  = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $k => $array) {
                $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                $tr[]    = [
                    $summary,
                    subjectClass::getShortName($array['subjectId']),
                    $array['direction'],
                    '无形资产',
                    zishu($array['rule'], 20),
                ];
            }
            $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'showSort' => true));
            $mode  = "<label class='radioLabel'>&nbsp;<input name='para' type='radio' value='没有无形资产记录' checked>&nbsp;没有无形资产记录</label>
<label class='radioLabel'>&nbsp;<input name='para' type='radio' value='有无形资产记录' disabled>&nbsp;有无形资产记录</label>";
            $space = space;
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <p class="nobottom-title">1、计提方式</p>
                <div class="flex-box">
                    $mode
                </div>
                {$space}
                <p class="nobottom-title">2、凭证模板</p>
                <div>
                    $table
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        eof;
            $height = 300;
        } elseif ($info['name'] == '摊销待摊费用') {
            $tr[] = ['摘要', '会计科目', '方向', '资产属性', '取数规则'];
            $all  = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $k => $array) {
                $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                $tr[]    = [
                    $summary,
                    subjectClass::getShortName($array['subjectId']),
                    $array['direction'],
                    '待摊费用',
                    zishu($array['rule'], 20),
                ];
            }
            $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'showSort' => true));
            $mode  = "<label class='radioLabel'>&nbsp;<input name='para' type='radio' value='没有待摊费用记录' checked>&nbsp;没有待摊费用记录</label>
<label class='radioLabel'>&nbsp;<input name='para' type='radio' value='有待摊费用记录' disabled>&nbsp;有待摊费用记录</label>";
            $space = space;
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <p class="nobottom-title">1、计提方式</p>
                <div class="flex-box">
                    $mode
                </div>
                {$space}
                <p class="nobottom-title">2、凭证模板</p>
                <div>
                    $table
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        eof;
            $height = 300;
        } elseif ($info['name'] == '结转未交增值税') {
            $tr[] = ['摘要', '会计科目', '方向', '说明'];
            $all  = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $k => $array) {
                $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                $tr[]    = [
                    $summary,
                    subjectClass::getShortName($array['subjectId']),
                    $array['direction'],
                    zishu($array['rule'], 20),
                ];
            }
            $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'showSort' => true));
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <div>
                    $table
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        eof;
            $height = 300;
        } elseif ($info['name'] == '计提税金') {
            $tr[] = ['', '摘要', '会计科目', '方向', '借方比率(%)', '贷方比率(%)'];
            $all  = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $k => $array) {
                $subject = query('subject', "id = '$array[subjectId]'");
                if ($array['direction'] == '借') {
                    $jie = $array['rule'];
                    $dai = '';
                } else {
                    $jie = '';
                    $dai = $array['rule'];
                }
                $direction     = select(array('name' => 'direction[]', 'value' => $array['direction'], 'title' => '请选择', 'option' => ['借', '贷'], 'class' => 'select'));
                $subjectSelect = text(array('name' => 'subjectName[]', 'value' => $subject['code'] . '-' . $subject['name'], 'class' => 'text', 'id' => $array['id'], 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => $array['subjectId'])) . <<<eof
<script>
$("#{$array['id']}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id)
       e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
                $tr[]          = [
                    "<span class='list-number'>" . ($k + 1) . "</span>" .
                    "<img class='action-but' title='删除此行' onclick='delTableRow(this)' src='" . root . "img/control/list_del.svg'>" .
                    hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                    hidden(array('name' => 'rule[]', 'value' => $array['rule'])),
                    text(array('name' => 'summary[]', 'class' => 'text', 'value' => $array['summary'])),
                    $subjectSelect,
                    $direction,
                    text(array('name' => 'jie[]', 'class' => 'text', 'blur' => 'rateOperate', 'value' => $jie)),
                    text(array('name' => 'dai[]', 'class' => 'text', 'blur' => 'rateOperate', 'value' => $dai))
                ];
            }
            $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'button' => true, 'method' => "addRow(this)"));
            $mode  = radio(['name' => 'para', 'checked' => $info['para'], 'value' => ['按月计提']]);
            $space = space;
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <p class="nobottom-title">1、计提方式</p>
                <div class="flex-box">
                    $mode
                </div>
                {$space}
                <p class="nobottom-title">2、凭证模板</p>
                <div>
                    $table
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        <script>
        function addRow(e) {
            $.post(root+'control/adIndex.html?cla=terminalTransfer&fun=addSysRow',{},function (res){
                     $(e).parent().before(res.html);
                     resetNumber($(e).parent().parent())
            },'json');
        }
        function rateOperate(e) {
            let name = $(e).attr('name')
            let tr = $(e).closest('tr')
            if(name === 'jie[]' && $(e).val()){
                tr.find("[name='dai[]']").val('')
                tr.find("[name='rule[]']").val($(e).val())
            }else if(name === 'dai[]' && $(e).val()){
                tr.find("[name='jie[]']").val('')
                tr.find("[name='rule[]']").val($(e).val())
            }
        }
        </script>
        eof;
            $height = 500;
        } elseif ($info['name'] == '地方水利基金' || $info['name'] == '印花税' || $info['name'] == '工会经费') {
            $tr[] = ['摘要', '会计科目', '方向', '取数规则'];
            $all  = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $k => $array) {
                $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                if ($info['name'] == '印花税') {
                    $subject       = query('subject', "id = '$array[subjectId]'");
                    $direction     = select(array('name' => 'direction[]', 'value' => $array['direction'], 'title' => '请选择', 'option' => ['借', '贷'], 'class' => 'select')) .
                        hidden(array('name' => 'mxId[]', 'value' => $array['id']));
                    $subjectSelect = text(array('name' => 'subjectName[]', 'value' => $subject['code'] . '-' . $subject['name'], 'class' => 'text', 'id' => $array['id'], 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => $array['subjectId'])) . <<<eof
<script>
$("#{$array['id']}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id)
       e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
                } else {
                    $direction     = $array['direction'];
                    $subjectSelect = subjectClass::getShortName($array['subjectId']);
                }
                $tr[] = [
                    $summary,
                    $subjectSelect,
                    $direction,
                    zishu($array['rule'], 20),
                ];
            }
            $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'showSort' => true));
            $mode  = radio(['name' => 'para', 'checked' => $info['para'], 'value' => ['按月计提']]);
            $space = space;
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <p class="nobottom-title">1、计提方式</p>
                <div class="flex-box">
                    $mode
                </div>
                {$space}
                <p class="nobottom-title">2、凭证模板</p>
                <div>
                    $table
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        eof;
            $height = 300;
        } elseif ($info['name'] == '计提所得税') {
            $tr[] = ['摘要', '会计科目', '方向'];
            $all  = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $k => $array) {
                $summary       = preg_replace("/{month}/", $month . "月", $array['summary']);
                $direction     = $array['direction'];
                $subjectSelect = subjectClass::getShortName($array['subjectId']);
                $tr[]          = [
                    $summary,
                    $subjectSelect,
                    $direction
                ];
            }
            $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'showSort' => true));
            $text  = "<p>财税[2022]13号文 执行期限为2022年1月1日至2024年12月31日对小型微利企业年应纳税所得额超过100万元但不超过300万元的部分，减按25%计入应纳税所得额，按20%的税率缴纳企业所得税。</p><p>财税[2023]6号文 执行期限为2023年1月1日至2024年12月31日 对小型微利企业年应纳税所得额不超过100万元的部分，减按25%计入应纳税所得额，按20%的税率缴纳企业所得税。</p><p>（小型微利企业是指从事国家非限制和禁止行业，且同时符合年度应纳税所得额不超过300万元、从业人数不超过300人、资产总额不超过5000万元等三个条件的企业。）</p>";
            $mode  = radio(['name' => 'para', 'checked' => $info['para'], 'value' => ['按小微企业标准计提' => '按小微企业标准计提' . componentClass::tipComponent($text, allowHTML: true), '按固定税率额计提' => '按固定税率额计提' . "<input type='text' class='width50' value='25'>%"]]);
            $space = space;
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <p class="nobottom-title">1、按季计提所得税</p>
                <p class="nobottom-title">2、计提方式</p>
                <div class="flex-box">
                    $mode
                </div>
                {$space}
                <p class="nobottom-title">3、凭证模板</p>
                <div>
                    $table
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        eof;
            $height = 400;
        } elseif ($info['name'] == '结转汇兑损益') {
            $tr[] = ['币种', '汇率'];
            $all  = find(array('table' => 'currency', 'where' => "coid = '" . self::$coid . "' order by time"));
            foreach ($all['array'] as $k => $array) {
                $rate = text(array('name' => 'rate[]', 'class' => 'text', 'other' => self::digitalFiltering(6), 'value' => $array['rate']));
                $tr[] = [
                    ($array['code'] . '(' . $array['name'] . ')') . hidden(array('name' => 'mxId[]', 'value' => $array['id'])),
                    $rate
                ];
            }
            $table   = $this->tableMany(array('tr' => $tr, 'end' => true, 'showSort' => true));
            $checked = $info['para'] == '包含损益科目' ? 'checked' : '';
            $mode    = "<label class='checkbox'><input name='para' type='checkbox' value='包含损益科目' " . $checked . "><span></span>&nbsp;包含损益科目</label>";
            $space   = space;
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <div class="flex-box">
                    $mode
                </div>
                {$space}
                <p class="nobottom-title">期末汇率设置</p>
                <div>
                    $table
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        eof;
            $height = 400;
        } else {
            $mode = radio(['name' => 'para', 'checked' => $info['para'], 'value' => ['收入费用合并结转', '收入费用分开结转']]);
            //生成表单
            $html   = <<<eof
        <form name="templateForm">
            <div class="layerList">
                <p class="nobottom-title">结转方式</p>
                <div class="flex-box">
                    $mode
                </div>
                <input type="hidden" name="id" value="$id">
            </div>
        </form>
        eof;
            $height = 200;
            $width  = 400;
        }

        $button = "<input class=\"button\" onclick=\"subForm('templateForm',root+'control/adIndex.html?cla=terminalTransfer&fun=settinSysSave')\" type=\"button\" value=\"保存\"/>";
        //返回
        return $this->layer(array("title" => $title, "height" => $height, "width" => $width, "html" => $html, "button" => $button));
    }

    /**
     * 配置保存
     */
    public function settinSysSave()
    {
        $id = $this->post('id') ?: self::getId();

        $mxIds      = $this->post('mxId');
        $directions = $this->post('direction');
        $subjectIds = $this->post('subjectId');
        $summarys   = $this->post('summary');
        $rules      = $this->post('rule');

        $field      = [
            'para' => $this->post('para'),
        ];
        $annotation = [
            'name' => '模板主表参数',
        ];

        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($info['id'])) {
            $json['warn'] = "该模板不存在";
        } else {
            $this->startTrans();

            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => $where
            ]);
            if (!static::is_null_array($mxIds)) {
                if ($info['name'] == '结转汇兑损益') {
                    $rate = $this->post('rate');
                    foreach ($mxIds as $k => $mxId) {
                        $mx = query('currency', "id = '$mxId'");
                        if ($mx['id']) {
                            $warn = static::update(array(
                                'table' => 'currency',
                                'field' => ['rate' => $rate[$k]],
                                'where' => "id = '$mxId'"
                            ));
                            if (!in_array($warn, ['新增成功', '更新成功'])) {
                                $json['warn'] = $warn;
                                break;
                            }
                        }
                    }
                } else {
                    foreach ($mxIds as $k => $mxId) {
                        $mx      = query(self::tableMx, "id = '$mxId'");
                        $mxField = [];
                        if (is_array($subjectIds)) $mxField['subjectId'] = $subjectIds[$k];
                        if (is_array($directions)) $mxField['direction'] = $directions[$k];
                        if (is_array($summarys)) $mxField['summary'] = $summarys[$k];
                        if (is_array($rules)) $mxField['rule'] = $rules[$k];

                        if (empty($mx['id'])) {
                            $warn = static::insert(array(
                                'table' => self::tableMx,
                                'field' => array_merge([
                                    'id'      => $mxId,
                                    'coid'    => self::$coid,
                                    'orderId' => $id,
                                ], $mxField)
                            ));
                        } else {
                            $warn = static::update(array(
                                'table' => self::tableMx,
                                'field' => $mxField,
                                'where' => "id = '$mxId'"
                            ));
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                    delete(array('table' => self::tableMx, 'where' => "orderId = '$id' and id not in ('" . implode("','", $mxIds) . "')"));
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);

    }

    /**
     * 添加一行
     * @return false|string
     */
    public function addSysRow()
    {
        $suiji         = suiji();
        $direction     = select(array('name' => 'direction[]', 'title' => '请选择', 'option' => ['借', '贷'], 'class' => 'select'));
        $subjectSelect = text(array('name' => 'subjectName[]', 'class' => 'text', 'id' => $suiji, 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => '')) . <<<eof
<script>
$("#{$suiji}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
        e.siblings("input[name='subjectId[]']").val(data.id)
        e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
        $tr[]          = [
            "<span class='list-number'></span>" .
            "<img class='action-but' title='删除此行' onclick='delTableRow(this)' src='" . root . "img/control/list_del.svg'>" .
            hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
            hidden(array('name' => 'rule[]', 'value' => '')),
            text(array('name' => 'summary[]', 'class' => 'text', 'value' => '')),
            $subjectSelect,
            $direction,
            text(array('name' => 'jie[]', 'class' => 'text', 'blur' => 'rateOperate', 'value' => '')),
            text(array('name' => 'dai[]', 'class' => 'text', 'blur' => 'rateOperate', 'value' => ''))
        ];
        $json['html']  = $this->tableMany(array('tr' => $tr, 'thead' => false));
        return json_encode($json, 320);
    }

    public function endPeriodVoucher($param)
    {
        $month      = $param['month'];
        $id         = $param['sourceId'];
        $preMonth   = date('Y-m', strtotime("-1 month", strtotime($month . '-01')));
        $multObj    = new multiColumnAccountClass();
        $balanceObj = new subjectBalanceClass();
        $profitObj  = new profitQuarterlyClass();
        $voucherObj = new voucherEditClass();
        $data       = [];
        //测算系统模板的结转金额
        $period_end_setting = query("period_end_setting", " coid = '" . self::$coid . "' and id = '$id' ");
        switch ($period_end_setting['name']) {
            case "计提工资":
                $totalMoney             = $voucherObj->calculateMoney('', '应付职工薪酬', $month);
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                    if ($array['direction'] == '借') {
                        $daiMoney = 0;
                        $jieMoney = $totalMoney;
                    } else {
                        $jieMoney = 0;
                        $daiMoney = $totalMoney;
                    }
                    $data[] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                }
                break;
            case "计提折旧":
                $totalMoney = 0;
                if ($period_end_setting['para'] == '有固定资产记录') {
                    // 对应会计期间的资产折旧明细的当月折旧
                    $endDate = $month . '-' . sprintf('%02d', date('t', strtotime($month)));
                    $result  = find(array(
                        "table" => "asset_depreciation_detail as detail join asset_depreciation as asset on detail.orderId = asset.id",
                        'field' => "detail.*",
                        "where" => "asset.coid = '" . self::$coid . "' and asset.month = '$month' and asset.state = '已通过' order by detail.list"
                    ));
                    foreach ($result['array'] as $array) {
                        $asset      = query('asset', " id = '{$array['atid']}' ");
                        $ratio      = assetManagementClass::monthRatio($asset['depreciationMethod'], $asset['discountYear'], $asset['money'], $asset['purchaseMoney'], $asset['depreciationMoney'], $asset['purchaseDate'], $endDate, 1);
                        $totalMoney += assetManagementClass::monthDecMoney($asset['depreciationMethod'], $asset['purchaseMoney'], $ratio / 100, $asset['purchaseDate'], $endDate, $asset['discountYear'], $asset['money'], $asset['depreciationMoney']);
                    }
                } else {
                    // 资产卡片折旧科目当月余额
                    $period_end_setting_all = find(['table' => 'asset_reg', 'where' => "state = '已确认' and disSubjectId <> '' order by time"]);
                    foreach ($period_end_setting_all['array'] as $array) {
                        $columns = [];
                        $multObj->loopSubjectIds($array['disSubjectId'], $columns);
                        foreach ($columns as $subjectId) {
                            $subject    = query('subject', "id = '$subjectId'");
                            $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                            $totalMoney += $balance;
                        }
                    }
                }
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                    if ($array['direction'] == '借') {
                        $daiMoney = 0;
                        $jieMoney = $totalMoney;
                    } else {
                        $jieMoney = 0;
                        $daiMoney = $totalMoney;
                    }
                    $data[] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                }
                break;
            case "摊销无形资产":
                $totalMoney = 0;

                $mainSubject = query('subject', "code = '1702'");
                $columns     = [];
                $multObj->loopSubjectIds($mainSubject['id'], $columns);
                foreach ($columns as $subjectId) {
                    $subject      = query('subject', "id = '$subjectId'");
                    $monthBalance = $balanceObj->monthBalance($preMonth, $preMonth, $subject['id']);
                    $totalMoney   += $monthBalance['daiMoney'];
                }
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                    if ($array['direction'] == '借') {
                        $daiMoney = 0;
                        $jieMoney = $totalMoney;
                    } else {
                        $jieMoney = 0;
                        $daiMoney = $totalMoney;
                    }
                    $data[] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                }
                break;
            case "摊销待摊费用":
                $totalMoney  = 0;
                $mainSubject = query('subject', "code = '1801'");
                $columns     = [];
                $multObj->loopSubjectIds($mainSubject['id'], $columns);
                foreach ($columns as $subjectId) {
                    $subject      = query('subject', "id = '$subjectId'");
                    $monthBalance = $balanceObj->monthBalance($preMonth, $preMonth, $subject['id']);
                    $totalMoney   += $monthBalance['daiMoney'];
                }
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                    if ($array['direction'] == '借') {
                        $daiMoney = 0;
                        $jieMoney = $totalMoney;
                    } else {
                        $jieMoney = 0;
                        $daiMoney = $totalMoney;
                    }
                    $data[] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                }
                break;
            case "结转未交增值税":
                $period_end_setting_detail = query("period_end_setting_detail", " orderId = '$period_end_setting[id]' ");
                $summary                   = preg_replace("/{month}/", $month . "月", $period_end_setting_detail['summary']);
                $unpaidMoney               = 0;
                // 未交
                $unpaidSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221002'");
                $columns       = [];
                $multObj->loopSubjectIds($unpaidSubject['id'], $columns);
                foreach ($columns as $subjectId) {
                    $subject     = query('subject', "id = '$subjectId'");
                    $balance     = $this->balanceOnlyMoney($month, $subject['id']);
                    $unpaidMoney += $balance;
                }
                $transferUnpaidSubject = query('subject', "coid = '" . self::$coid . "' and code = '222100103'");
                $data[]                = ['summary' => $summary, 'subjectId' => $transferUnpaidSubject['id'], 'jieMoney' => $unpaidMoney, 'daiMoney' => 0];
                $data[]                = ['summary' => $summary, 'subjectId' => $unpaidSubject['id'], 'jieMoney' => 0, 'daiMoney' => $unpaidMoney];
                $advanceMoney          = 0;
                // 预交
                $advanceSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221018'");
                $columns        = [];
                $multObj->loopSubjectIds($advanceSubject['id'], $columns);
                foreach ($columns as $subjectId) {
                    $subject      = query('subject', "id = '$subjectId'");
                    $balance      = $this->balanceOnlyMoney($month, $subject['id']);
                    $advanceMoney += $balance;
                }
                $data[]                 = ['summary' => $summary, 'subjectId' => $advanceSubject['id'], 'jieMoney' => 0, 'daiMoney' => $advanceMoney];
                $transferAdvanceSubject = query('subject', "coid = '" . self::$coid . "' and code = '222100109'");
                $data[]                 = ['summary' => $summary, 'subjectId' => $transferAdvanceSubject['id'], 'jieMoney' => $unpaidMoney, 'daiMoney' => 0];
                break;
            case "计提税金":
                $totalMoney = 0;
                // 应交
                $payableSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221001'");
                $columns        = [];
                $multObj->loopSubjectIds($payableSubject['id'], $columns);
                foreach ($columns as $subjectId) {
                    $subject    = query('subject', "id = '$subjectId'");
                    $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                    $totalMoney += $balance;
                }
                // 未交
                $unpaidSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221002'");
                $columns       = [];
                $multObj->loopSubjectIds($unpaidSubject['id'], $columns);
                foreach ($columns as $subjectId) {
                    $subject    = query('subject', "id = '$subjectId'");
                    $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                    $totalMoney += $balance;

                }
                // (应交+未交)*借方比率
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                    if ($array['direction'] == '借') {
                        $daiMoney = 0;
                        $jieMoney = round($totalMoney * (floatval($array['rule']) / 100), 2);
                    } else {
                        $jieMoney = 0;
                        $daiMoney = round($totalMoney * (floatval($array['rule']) / 100), 2);
                    }
                    $data[] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                }
                break;
            case "地方水利基金":
            case "工会经费":
                $totalMoney             = 0;
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' and rule <> '自动找平' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $columns = [];
                    $multObj->loopSubjectIds($array['subjectId'], $columns);
                    foreach ($columns as $subjectId) {
                        $subject    = query('subject', "id = '$subjectId'");
                        $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                        $totalMoney += $balance;
                    }
                }
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                    if ($array['direction'] == '借') {
                        $daiMoney = 0;
                        $jieMoney = $totalMoney;
                    } else {
                        $jieMoney = 0;
                        $daiMoney = $totalMoney;
                    }
                    $data[] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                }
                break;
            case "计提所得税":
                $startMonth = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 1);
                $endMonth   = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 3);
                $profit     = $profitObj->totalProfit('利润总额', $startMonth, $endMonth);
                $profit     = $profit['balance'];
                $p          = "1.本年累计利润总额(利润表利润总额)：" . $profit;
                $p          .= "2.应纳税所得额 = 利润总额 - 弥补以前年度亏损= {$profit} - 0.00 = " . $profit;
                // 应交所得税科目
                $taxPayableSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221006'");
                $columns           = [];
                $multObj->loopSubjectIds($taxPayableSubject['id'], $columns);
                $daiMoney = $totalMoney = 0;
                foreach ($columns as $subjectId) {
                    $subject = query('subject', "id = '$subjectId'");
                    //应交所得税科目贷方发生额
                    $monthBalance = $balanceObj->monthBalance($month, $month, $subject['id']);
                    $daiMoney     += $monthBalance['daiMoney'];
                    // 应交所得税期初累计发生额
                    $balance    = $this->balanceOnlyMoney($preMonth, $subject['id']);
                    $totalMoney += $balance;
                }
                // 已提金额
                $amount = $daiMoney + $totalMoney;
                $p      .= "3.已计提金额 = 应交所得税科目贷方发生额（对方科目为所得税费用）+ 应交所得税期初累计发生额 = " . $amount;
                if ($profit > 300 * 10000) {
                    $taxation = 100;
                    $taxRate  = 25;
                    $p        .= "4.计提金额计算规则：300万元 < 应纳税所得额，计提金额 = 应纳税所得额 * 100%（计税比例）* 25%（税率）- 已计提金额（计算结果大于0时计提，否则为0不计提）";
                } elseif ($profit > 100 * 10000 && $profit <= 300 * 10000) {
                    $taxation = 25;
                    $taxRate  = 20;
                    $p        .= "4.计提金额计算规则：100万元 < 应纳税所得额 <= 300万元，计提金额 = 应纳税所得额 * 25%（计税比例）* 20%（税率）- 已计提金额（计算结果大于0时计提，否则为0不计提）";
                } else {
                    $taxation = 25;
                    $taxRate  = 10;
                    $p        .= "4.计提金额计算规则：0 < 应纳税所得额 <= 100万元，计提金额 = 应纳税所得额 * 25%（计税比例）* 10%（税率）- 已计提金额（计算结果大于0时计提，否则为0不计提）";

                }
                $money                  = round($profit * ($taxation / 100) * ($taxRate / 100) - $amount, 2);
                $p                      .= "5.计提金额：" . $money;
                $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                foreach ($period_end_setting_all['array'] as $array) {
                    $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                    if ($array['direction'] == '借') {
                        $daiMoney = 0;
                        $jieMoney = $money;
                    } else {
                        $jieMoney = 0;
                        $daiMoney = $money;
                    }
                    $data[] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                }
                break;
            case "结转汇兑损益":
                $summary = preg_replace("/{month}/", $month . "月", "结转{month}汇兑损益");
                // 查询本期存在外币的凭证，计算损益差额
                $result     = find(array(
                    "table" => "voucher_detail as detail join voucher as vou on detail.orderId = vou.id",
                    'field' => "detail.*",
                    "where" => "vou.coid = '" . self::$coid . "' and date_format(vou.recordDate,'%Y-%m') = '$month' and vou.workFlow <> '已作废' and detail.currencyId <> '' order by detail.list"
                ));
                $totalMoney = 0;
                foreach ($result['array'] as $array) {
                    $currency   = query("currency", " id = '" . $array['currencyId'] . "' ");
                    $seedMoney  = round($array['money'] / $array['rate']);
                    $money      = self::centToYuan($array['money'] - round($seedMoney * $currency['rate']));
                    $data[]     = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => 0, 'daiMoney' => $money, 'voucherId' => $array['id']];
                    $totalMoney += $money;
                }
                $rule = companyClass::returnRule(1);
                if ($rule == 'enterpriseRule') {
                    $subjectCode = '6603003';
                } else {
                    $subjectCode = '5603003';
                }
                $subject = query('subject', "coid = '" . self::$coid . "' and code = '$subjectCode'");
                $data[]  = ['summary' => $summary, 'subjectId' => $subject['id'], 'jieMoney' => $totalMoney, 'daiMoney' => 0];
                break;
            case "结转本期损益":
                $summary = preg_replace("/{month}/", $month . "月", "结转{month}损益");
                $income  = $cost = 0;
                //查询损益类本期余额合计
                $subject_all = find(['table' => 'subject', 'where' => "coid = '" . self::$coid . "' and type = '损益类' order by list"]);
                foreach ($subject_all['array'] as $array) {
                    $columns = [];
                    $multObj->loopSubjectIds($array['id'], $columns);
                    foreach ($columns as $subjectId) {
                        $subject = query('subject', "id = '$subjectId'");
                        $balance = $this->balanceOnlyMoney($month, $subject['id']);
                        if ($subject['direction'] == '贷') {
                            $income   += $balance;
                            $jieMoney = $balance;
                            $daiMoney = 0;
                        } else {
                            $cost     += $balance;
                            $jieMoney = 0;
                            $daiMoney = $balance;
                        }
                        if ($jieMoney > 0 || $daiMoney > 0) {
                            $data[] = ['summary' => $summary, 'subjectId' => $subject['id'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                        }
                    }
                }
                $p     = "<p>1.本期收入合计：{$income}</p><p>2.本期成本费用合计：{$cost}</p>";
                $money = $income - $cost;
                $rule  = companyClass::returnRule(1);
                if ($rule == 'enterpriseRule') {
                    $subjectCode = '4103';
                } else {
                    $subjectCode = '3103';
                }
                $subject = query('subject', "coid = '" . self::$coid . "' and code = '$subjectCode'");
                $data[]  = ['summary' => $summary, 'subjectId' => $subject['id'], 'jieMoney' => 0, 'daiMoney' => $money];
                break;
            default:
                // 自定义模板
                if($period_end_setting['isDel'] == 1){
                    $subjectAssetBalanceClassObj = new subjectAssetBalanceClass();
                    $level = query("period_end_setting_detail"," orderId = '$period_end_setting[id]' and rule = '自动找平' ");
                    $level_list = 0;
                    $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' order by list"]);
                    $sumMoney = 0;
                    foreach ($period_end_setting_all['array'] as $k=>$array) {
                        $summary = preg_replace("/{month}/", $month . "月", $array['summary']);
                        if($array['rule'] == '自动找平'){
                            $level_list = $k;
                            $data[$k] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => 0, 'daiMoney' => 0];
                        }else {
                            $money   = 0;
                            $formula = json_decode($array['formula'], true);
                            foreach ((array)$formula as $arr) {
                                $columns = [];
                                $multObj->loopSubjectIds($arr['subjectId'], $columns);
                                $totalMoney = 0;
                                switch ($arr['rule']) {
                                    case '余额':
                                        foreach ($columns as $subjectId) {
                                            $subject    = query('subject', "id = '$subjectId'");
                                            $res        = $subjectAssetBalanceClassObj->balance($arr['khid'], $arr['supplierId'], $arr['staffId'], $arr['departmentId'], $arr['materialId'], $arr['cashId'], $arr['projectId'], $month, $subject['id']);
                                            $totalMoney += $res['balance'];
                                        }
                                        break;
                                    case '末级科目借方余额':
                                        $last       = end($columns);
                                        $subject    = query('subject', "id = '$last[subjectId]'");
                                        $res        = $subjectAssetBalanceClassObj->balance($arr['khid'], $arr['supplierId'], $arr['staffId'], $arr['departmentId'], $arr['materialId'], $arr['cashId'], $arr['projectId'], $month, $subject['id']);
                                        $totalMoney = $res['jieMoney'];
                                        break;
                                    case '末级科目贷方余额':
                                        $last       = end($columns);
                                        $subject    = query('subject', "id = '$last[subjectId]'");
                                        $res        = $subjectAssetBalanceClassObj->balance($arr['khid'], $arr['supplierId'], $arr['staffId'], $arr['departmentId'], $arr['materialId'], $arr['cashId'], $arr['projectId'], $month, $subject['id']);
                                        $totalMoney = $res['daiMoney'];
                                        break;
                                    case '本级科目借方余额':
                                        $subject    = query('subject', "id = '$arr[subjectId]'");
                                        $res        = $subjectAssetBalanceClassObj->balance($arr['khid'], $arr['supplierId'], $arr['staffId'], $arr['departmentId'], $arr['materialId'], $arr['cashId'], $arr['projectId'], $month, $subject['id']);
                                        $totalMoney = $res['jieMoney'];
                                        break;
                                    case '本级科目贷方余额':
                                        $subject    = query('subject', "id = '$arr[subjectId]'");
                                        $res        = $subjectAssetBalanceClassObj->balance($arr['khid'], $arr['supplierId'], $arr['staffId'], $arr['departmentId'], $arr['materialId'], $arr['cashId'], $arr['projectId'], $month, $subject['id']);
                                        $totalMoney = $res['daiMoney'];
                                        break;
                                    case '本级科目借方发生':
                                        $subject    = query('subject', "id = '$arr[subjectId]'");
                                        $res        = $subjectAssetBalanceClassObj->monthBalance($arr['khid'], $arr['supplierId'], $arr['staffId'], $arr['departmentId'], $arr['materialId'], $arr['cashId'], $arr['projectId'], $month, $month, $subject['id']);
                                        $totalMoney = $res['jieMoney'];
                                        break;
                                    case '本级科目贷方发生':
                                        $subject    = query('subject', "id = '$arr[subjectId]'");
                                        $res        = $subjectAssetBalanceClassObj->monthBalance($arr['khid'], $arr['supplierId'], $arr['staffId'], $arr['departmentId'], $arr['materialId'], $arr['cashId'], $arr['projectId'], $month, $month, $subject['id']);
                                        $totalMoney = $res['daiMoney'];
                                        break;
                                }
                                if ($arr['calculate'] && $arr['val']) {
                                    $totalMoney = $arr['val'] == 0 ? 0 : ($arr['calculate'] == '/' ? $totalMoney / $arr['val'] : $totalMoney * $arr['val']);
                                }
                                if ($arr['operator'] == '-') {
                                    $money -= $totalMoney;
                                } else {
                                    $money += $totalMoney;
                                }
                            }

                            if ($array['direction'] == '借') {
                                $daiMoney = 0;
                                $jieMoney = round($money, 2);
                            } else {
                                $jieMoney = 0;
                                $daiMoney = round($money, 2);
                            }
                            $sumMoney += $money;
                            $data[$k] = ['summary' => $summary, 'subjectId' => $array['subjectId'], 'jieMoney' => $jieMoney, 'daiMoney' => $daiMoney];
                        }
                    }
                    // 存在自动找平
                    if($level['id']){
                        if ($level['direction'] == '借') {
                            $data[$level_list]['jieMoney'] = $sumMoney;
                        } else {
                            $data[$level_list]['daiMoney'] = $sumMoney;
                        }
                    }
                }

        }
        return $data;
    }

    /**
     * 系统模板
     * @return string
     */
    public function custom(): string
    {
        $month = $this->get('id');
        //第一阶段
        $all = find(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "' and isDel = 1 order by list asc"));
        $li  = <<<eof
             <li>
                 <div class="tag-contain tag-contain-add" title="新增模板" onclick="layer('terminalTransfer','settingPage',{id:''})">
                    <div class="tag-contain-add-sign">+</div>
                 </div>
            </li>
eof;
        foreach ($all['array'] as $array) {
            $btn     = <<<eof
<span><img class="set-ico" onclick="layer('terminalTransfer','settingPage',{id:'{$array['id']}'})" alt="" src="{$this->root}img/control/setting.svg">
<img class="set-ico" onclick="layer('terminalTransfer', 'operate', {'act': 'del',id:'{$array['id']}'})" alt="" src="{$this->root}img/control/singleDel.svg"></span>
<span class="spanButton" onclick="layer('terminalTransfer','voucherPage',{method:'endPeriod', month:'{$month}', sourceId:'{$array['id']}'})">生成凭证</span>
eof;
            $money   = '&nbsp;';
            $voucher = query('voucher', "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and sourceId = '$array[id]' and source = '期末结转'");
            if ($voucher['id']) {
                $money = round(self::centToYuan($voucher['money']), 2);
                $btn   = <<<eof
<span class="spanButton" onclick="layer('terminalTransfer','voucherPage',{id:'{$voucher['id']}'})">查看凭证</span>
eof;
            }

            $li .= <<<eof
            <li>
             <div class="tag-contain">
                   <div class="tag-contain-title">
                         <span class="tag-contain-title-text">{$array['name']}</span>
                   </div>
                   <div class="tag-contain-body">
                         <ul class="tag-contain-ul">
                             <li>$money</li>
                         </ul>
                   </div>
                   <div class="tag-contain-foot"></div>
                   <div class="tag-edit-content">
                         $btn
                   </div>
             </div>
            </li>
eof;

        }
        $content      = <<<eof
    <ul class='tag-list-ul'>
        $li
    </ul>
eof;
        $json['html'] = <<<eof
<div class="setting-content">
    {$content}
</div>
<input name="month" type="hidden" value="$month">
eof. $this->settingStyle();
        //控件
        return json_encode($json, 320);
    }

    public function settingPage()
    {
        $id         = $this->post('id');
        $info       = query(self::table, "id = '$id'");
        $wordSelect = idSelect(array('name' => 'voucherWordId', 'class' => 'select width100', 'value' => $info['voucherWordId'], 'title' => '请选择', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "'", 'sqlId' => 'id', 'sqlField' => 'word'));
        $tr[]       = ['', '摘要', '会计科目', '方向', '公式'];
        $all        = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($all['array'] as $k => $array) {
            $subject       = query('subject', "id = '$array[subjectId]'");
            $direction     = select(array('name' => 'direction[]', 'value' => $array['direction'], 'title' => '请选择', 'option' => ['借', '贷'], 'class' => 'select'));
            $subjectSelect = text(array('name' => 'subjectName[]', 'value' => $subject['code'] . '-' . $subject['name'], 'class' => 'text', 'id' => $array['id'], 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => $array['subjectId'])) . <<<eof
<script>
$("#{$array['id']}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id)
       e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
            $formula       = "<span class='smallButton' onclick=\"editFormula('{$array['id']}_formula')\">编辑公式</span>";
            $tr[]          = [
                "<span class='list-number'>" . ($k + 1) . "</span>" .
                "<img class='action-but' title='删除此行' onclick='delTableRow(this)' src='" . root . "img/control/list_del.svg'>" .
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'formula[]', 'id' => $array['id'] . '_formula', 'value' => base64_encode($array['formula']))),
                text(array('name' => 'summary[]', 'class' => 'text', 'value' => $array['summary'])),
                $subjectSelect,
                $direction,
                $formula
            ];
        }
        $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'button' => true, 'method' => "addRow(this)"));
        //生成表单
        $html   = <<<eof
<form name="templateForm">
<div class="layerList">
    <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;margin: 10px auto;">
        <div>类型：<span>期末结转(自定义)</span></div>
        <div>模板名称：<input name="templateName" type="text" class="width200" value="{$info['name']}" /></div>
        <div>凭证字：$wordSelect</div>
    </div>
    <div>
        $table
    </div>
    <input type="hidden" name="id" value="$id">
</div>
<script>
function addRow(e) {
    $.post(root+'control/adIndex.html?cla=terminalTransfer&fun=addRow',{},function (res){
             $(e).parent().before(res.html);
             resetNumber($(e).parent().parent())
    },'json');
}
function editFormula(id) {
    let tr = $('#'+id).closest('tr')
    let formula = $('#'+id).val()
    let subjectId = tr.find("[name='subjectId[]']").val()
    layer('terminalTransfer','editFormula',{id:id, subjectId:subjectId, formula:formula})
}
function setFormula(id) {
    $.post(root+'control/adIndex.html?cla=terminalTransfer&fun=comData',$("form[name='editFormulaForm']").serialize(),function(res) {
       if (res.warn == 2) {
            $('#terminalTransferEditFormula').remove()
            $('#'+id).val(res.formula)
            console.log($('#'+id))
        } else {
            warn(res.warn);
        }
    },'json');
}
function addFormula(e) {
    $.post(root+'control/adIndex.html?cla=terminalTransfer&fun=addFormula',{},function (res){
             $(e).parent().before(res.html);
             resetNumber($(e).parent().parent())
    },'json');
}
</script>
</form>
eof;
        $button = "<input class=\"button\" onclick=\"subForm('templateForm',root+'control/adIndex.html?cla=terminalTransfer&fun=settingSave')\" type=\"button\" value=\"保存\"/>";
        //返回
        return $this->layer(array("title" => "编辑", "height" => 600, "width" => 900, "html" => $html, "button" => $button));
    }

    /**
     * 添加一行
     * @return false|string
     */
    public function addRow()
    {
        $suiji         = suiji();
        $direction     = select(array('name' => 'direction[]', 'title' => '请选择', 'option' => ['借', '贷'], 'class' => 'select'));
        $subjectSelect = text(array('name' => 'subjectName[]', 'class' => 'text', 'id' => $suiji, 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => '')) . <<<eof
<script>
$("#{$suiji}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
        e.siblings("input[name='subjectId[]']").val(data.id)
        e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
        $formula       = "<span class='smallButton' onclick=\"editFormula('{$suiji}_formula')\">编辑公式</span>";
        $tr[]          = [
            "<span class='list-number'></span>" .
            "<img class='action-but' title='删除此行' onclick='delTableRow(this)' src='" . root . "img/control/list_del.svg'>" .
            hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
            hidden(array('name' => 'formula[]', 'id' => $suiji . '_formula', 'value' => '')),
            text(array('name' => 'summary[]', 'class' => 'text')),
            $subjectSelect,
            $direction,
            $formula
        ];
        $json['html']  = $this->tableMany(array('tr' => $tr, 'thead' => false));
        return json_encode($json, 320);
    }

    /*编辑公式*/
    public function editFormula()
    {
        $id        = $this->post('id');
        $subjectId = $this->post('subjectId');
        $all       = json_decode(base64_decode($this->post('formula')), true);
        $tr[]      = ['', '运算符', '会计科目', '辅助核算', '取数规则', '运算', '数值'];
        foreach ((array)$all as $k => $array) {
            $array['id']   = self::getId();
            $subject       = query('subject', "id = '$array[subjectId]'");
            $subjectSelect = text(array('name' => 'subjectName[]', 'value' => $subject['code'] . '-' . $subject['name'], 'class' => 'text', 'id' => $array['id'], 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => $array['subjectId'])) . <<<eof
<script>
$("#{$array['id']}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id)
       e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
            $operator      = select(array('name' => 'operator[]', 'value' => $array['operator'], 'title' => '请选择', 'option' => ['+', '-'], 'class' => 'select'));
            $rule          = select(array('name' => 'rule[]', 'value' => $array['rule'], 'title' => '请选择', 'option' => ['余额', '末级科目借方余额', '末级科目贷方余额', '本级科目借方余额', '本级科目贷方余额', '本级科目借方发生', '本级科目贷方发生', '找平'], 'class' => 'select'));
            $calculate     = select(array('name' => 'calculate[]', 'value' => $array['calculate'], 'title' => '请选择', 'option' => ['*', '/'], 'class' => 'select'));
            $val           = text(array('name' => 'val[]', 'class' => 'text', 'other' => self::digitalFiltering(), 'value' => $array['val']));
            $assistName    = '';
            if ($subject['assistAccount'] == '是') {
                $assistName = '';
                if (!empty($array['khid'])) {
                    $kehu       = query('kehu', "khid = '$array[khid]'");
                    $assistName .= '_' . $kehu['orderNo'] . $kehu['companyName'];
                }
                if (!empty($array['supplierId'])) {
                    $supplier   = query('supplier', "id = '$array[supplierId]'");
                    $assistName .= '_' . $supplier['code'] . $supplier['name'];
                }
                if (!empty($array['staffId'])) {
                    $staff      = query('staff', "stid = '$array[staffId]'");
                    $assistName .= '_' . $staff['orderNo'] . $staff['name'];
                }
                if (!empty($array['departmentId'])) {
                    $department = query('department', "id = '$array[departmentId]'");
                    $assistName .= '_' . $department['name'];
                }
                if (!empty($array['materialId'])) {
                    $assistName .= '_' . materialClass::getName($array['materialId'], '');
                }
                if (!empty($array['projectId'])) {
                    $project    = query('project', "id = '$array[projectId]'");
                    $assistName .= '_' . $project['orderNo'] . $project['name'];
                }
                if (!empty($array['cashId'])) {
                    $cash       = query('cash', "id = '$array[cashId]'");
                    $assistName .= '_' . $cash['code'] . $cash['name'];
                }
            }
            $assistName = ' ' . ltrim($assistName, '_');
            $assist     = "<div class='assist-div'>" . text(array('name' => 'assistName[]', 'value' => $assistName, 'data' => ['id' => $array['id']], 'class' => 'text', 'click' => 'getAssit')) . "</div>" .
                hidden(array('name' => 'khid[' . $array['id'] . ']', 'value' => $array['khid'])) .
                hidden(array('name' => 'supplierId[' . $array['id'] . ']', 'value' => $array['supplierId'])) .
                hidden(array('name' => 'staffId[' . $array['id'] . ']', 'value' => $array['staffId'])) .
                hidden(array('name' => 'projectId[' . $array['id'] . ']', 'value' => $array['projectId'])) .
                hidden(array('name' => 'materialId[' . $array['id'] . ']', 'value' => $array['materialId'])) .
                hidden(array('name' => 'cashId[' . $array['id'] . ']', 'value' => $array['cashId'])) .
                hidden(array('name' => 'departmentId[' . $array['id'] . ']', 'value' => $array['departmentId']));
            $tr[]       = [
                "<span class='list-number'>" . ($k + 1) . "</span>" .
                "<img class='action-but' title='删除此行' onclick='delTableRow(this)' src='" . root . "img/control/list_del.svg'>" .
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])),
                $operator,
                $subjectSelect,
                $assist,
                $rule,
                $calculate,
                $val
            ];
        }
        if (count((array)$all) == 0 && $subjectId) {
            $array['id']   = self::getId();
            $subject       = query('subject', "id = '$subjectId'");
            $subjectSelect = text(array('name' => 'subjectName[]', 'value' => $subject['code'] . '-' . $subject['name'], 'class' => 'text', 'id' => $array['id'], 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => $subjectId)) . <<<eof
<script>
$("#{$array['id']}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id)
       e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
            $operator      = select(array('name' => 'operator[]', 'value' => '+', 'title' => '请选择', 'option' => ['+', '-'], 'class' => 'select'));
            $rule          = select(array('name' => 'rule[]', 'value' => '余额', 'title' => '请选择', 'option' => ['余额', '末级科目借方余额', '末级科目贷方余额', '本级科目借方余额', '本级科目贷方余额', '本级科目借方发生', '本级科目贷方发生', '找平'], 'class' => 'select'));
            $calculate     = select(array('name' => 'calculate[]', 'value' => '', 'title' => '请选择', 'option' => ['*', '/'], 'class' => 'select'));
            $val           = text(array('name' => 'val[]', 'class' => 'text', 'other' => self::digitalFiltering(), 'value' => ''));
            $assistName    = '';
            $assist        = "<div class='assist-div'>" . text(array('name' => 'assistName[]', 'value' => $assistName, 'data' => ['id' => $array['id']], 'class' => 'text', 'click' => 'getAssit')) . "</div>" .
                hidden(array('name' => 'khid[' . $array['id'] . ']', 'value' => '')) .
                hidden(array('name' => 'supplierId[' . $array['id'] . ']', 'value' => '')) .
                hidden(array('name' => 'staffId[' . $array['id'] . ']', 'value' => '')) .
                hidden(array('name' => 'projectId[' . $array['id'] . ']', 'value' => '')) .
                hidden(array('name' => 'materialId[' . $array['id'] . ']', 'value' => '')) .
                hidden(array('name' => 'cashId[' . $array['id'] . ']', 'value' => '')) .
                hidden(array('name' => 'departmentId[' . $array['id'] . ']', 'value' => ''));
            $tr[]          = [
                "<span class='list-number'>1</span>" .
                "<img class='action-but' title='删除此行' onclick='delTableRow(this)' src='" . root . "img/control/list_del.svg'>" .
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])),
                $operator,
                $subjectSelect,
                $assist,
                $rule,
                $calculate,
                $val
            ];
        }
        $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'button' => true, 'method' => "addFormula(this)"));
        //生成表单
        $html   = <<<eof
<form name="editFormulaForm">
<div class="layerList">
    <div class="flex-box mar10">
        <div class="nobottom-title">编辑公式</div>
    </div>
    <div>
        $table
    </div>
    <input type="hidden" name="id" value="$id">
</div>
<style>
.assist-div{position: relative;}
.auxiliary-accounting,.currency-assit{padding: 15px 10px;position: absolute;background-color: #f2f2f2;width: 300px;box-shadow: 0 3px 10px 0 #888;z-index: 100;}
.auxiliary-accounting-button input[type='button']{
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    text-align: center;
    margin-right: 6px;
    cursor: pointer;
    user-select: none;
    background-color: white;
    padding: 3px 15px;
}
.auxiliary-accounting-button{text-align: right}
.auxiliary-accounting-button input[type='button']:hover{
    background-color: #3577FF;color: white;border-color: #3577FF;
}
.account-item{display: flex;margin-bottom: 15px}
.account-item-title{text-align: right;width: 60px}
.account-item-value{flex: 1;text-align: left}
.currency-assit .account-item-title{width: 50px}
.auxiliary-accounting-button .confirm-button{border-color: #3577FF !important;background-color:#3577FF !important;color: white }
.auxiliary-accounting-button .confirm-button:hover{border-color: #6aacfb !important;background-color:#6aacfb !important;color: white }
</style>
<script>
function getAssit(e) {
    hideAssist()
    let tr = $(e).closest('tr')
    let td = $(e).closest('td')
    let id = $(e).data('id')
    let subjectId = tr.find("[name='subjectId[]']").val()
    let khid = td.find("[name='khid["+id+"]']").val()
    let supplierId = td.find("[name='supplierId["+id+"]']").val()
    let staffId = td.find("[name='staffId["+id+"]']").val()
    let projectId = td.find("[name='projectId["+id+"]']").val()
    let materialId = td.find("[name='materialId["+id+"]']").val()
    let cashId = td.find("[name='cashId["+id+"]']").val()
    let departmentId = td.find("[name='departmentId["+id+"]']").val()
    $.post(root+'control/adIndex.html?cla=terminalTransfer&fun=getAssit',{id:id, subjectId:subjectId, khid:khid, supplierId:supplierId, staffId:staffId, projectId:projectId, materialId:materialId, cashId:cashId, departmentId:departmentId},function (res){
             $(e).parent().append(res.html);
    },'json');
}
$(document).on('click', function(event) {
   if (!$(event.target).closest('.assist-div').length && !$(event.target).is('.assist-div') && !$(event.target).closest('.bigautocomplete-layout').length && !$(event.target).is('.bigautocomplete-layout')) {
       hideAssist()
   }
});
/**
 * 辅助核算的输入框焦点
 */
function switchAssetInput(e) {
    let nextElement = $(e).parent().parent().next(".account-item");
    if (nextElement.length > 0) {
        nextElement.find("input").focus();
    }
}
/**
 * 辅助核算的弹窗取消
 */
function hideAssist() {
    $('.auxiliary-accounting').remove();
}
//辅助核算确认
function confirmAssistTransfer(mxId, subjectId, isCurrency,subjectName) {
    let assetTitle = '';
    let id = '';
    let flag = false;
    let list = 0;
    let objType = '';
    let idArr = [];
    let row = $("[data-id='" + mxId + "']").parent().parent();
    $(".assist-div .auxiliary-accounting").find("input[type='text']").each(function (index) {
        if (!$(this).val()) {
            msg('请选择完辅助核算', 'error');
            flag = true;
            return false;
        }
        id = $(this).data('id')
        idArr.push(id);
        list++;
        objType = $(this).data('type');
        row.find("[name='" + objType + "[" + mxId + "]']").val(id);
        if (index > 0) {
            assetTitle += '_';
        }
        assetTitle += $(this).val()
    })
    if (flag) {
        return false;
    }
    idArr = idArr.sort();
    // row.find(".assist-name").show();
    // row.find(".assist-name").html(str);
    $("[data-id='" + mxId + "']").val(assetTitle)
    hideAssist();
}
</script>
</form>
eof;
        $button = "<input class=\"button\" onclick=\"setFormula('$id')\" type=\"button\" value=\"保存\"/>";
        //返回
        return $this->layer(array("title" => "编辑", "height" => 600, "width" => 900, 'zindex' => 10, "html" => $html, "button" => $button));
    }

    /**
     * 组合公式数据
     */
    public function comData()
    {
        $mxIds        = $this->post('mxId');
        $operator     = $this->post('operator');
        $subjectIds   = $this->post('subjectId');
        $rule         = $this->post('rule');
        $calculate    = $this->post('calculate');
        $val          = $this->post('val');
        $khid         = $this->post('khid');
        $supplierId   = $this->post('supplierId');
        $staffId      = $this->post('staffId');
        $projectId    = $this->post('projectId');
        $materialId   = $this->post('materialId');
        $cashId       = $this->post('cashId');
        $departmentId = $this->post('departmentId');

        $data = [];
        $makeLevel = 0;
        if (is_array($mxIds) && count($mxIds) > 0) {
            foreach ($mxIds as $k => $id) {
                if($rule[$k] == '找平'){
                    $makeLevel++;
                }
                $data[] = [
                    'operator'     => $operator[$k],
                    'subjectId'    => $subjectIds[$k],
                    'rule'         => $rule[$k],
                    'calculate'    => $calculate[$k],
                    'val'          => $val[$k],
                    'khid'         => $khid[$id],
                    'supplierId'   => $supplierId[$id],
                    'staffId'      => $staffId[$id],
                    'projectId'    => $projectId[$id],
                    'materialId'   => $materialId[$id],
                    'cashId'       => $cashId[$id],
                    'departmentId' => $departmentId[$id],
                ];
            }
        }
        if($makeLevel > 1){
            $json['warn'] = '一个模板中只能设置一个找平规则';
        }else{
            $json['warn'] = 2;
            $json['formula'] = empty($data)?'':base64_encode(json_encode($data,320));
        }

        return json_encode($json, 320);
    }

    /**
     * 添加一行
     * @return false|string
     */
    public function addFormula()
    {
        $id            = self::getId();
        $subjectSelect = text(array('name' => 'subjectName[]', 'value' => '', 'class' => 'text', 'id' => $id, 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => '')) . <<<eof
<script>
$("#{$id}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id)
       e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
        $operator      = select(array('name' => 'operator[]', 'value' => ' + ', 'title' => '请选择', 'option' => ['+', '-'], 'class' => 'select'));
        $rule          = select(array('name' => 'rule[]', 'value' => '余额', 'title' => '请选择', 'option' => ['余额', '末级科目借方余额', '末级科目贷方余额', '本级科目借方余额', '本级科目贷方余额', '本级科目借方发生', '本级科目贷方发生', '找平'], 'class' => 'select'));
        $calculate     = select(array('name' => 'calculate[]', 'value' => '', 'title' => '请选择', 'option' => ['*', '/'], 'class' => 'select'));
        $val           = text(array('name' => 'val[]', 'class' => 'text', 'other' => self::digitalFiltering(), 'value' => ''));
        $assistName    = '';
        $assist        = "<div class='assist-div'>" . text(array('name' => 'assistName[]', 'value' => $assistName, 'data' => ['id' => $id], 'class' => 'text', 'click' => 'getAssit')) . "</div>" .
            hidden(array('name' => 'khid[' . $id . ']', 'value' => '')) .
            hidden(array('name' => 'supplierId[' . $id . ']', 'value' => '')) .
            hidden(array('name' => 'staffId[' . $id . ']', 'value' => '')) .
            hidden(array('name' => 'projectId[' . $id . ']', 'value' => '')) .
            hidden(array('name' => 'materialId[' . $id . ']', 'value' => '')) .
            hidden(array('name' => 'cashId[' . $id . ']', 'value' => '')) .
            hidden(array('name' => 'departmentId[' . $id . ']', 'value' => ''));
        $tr[]          = [
            "<span class='list-number'></span>" .
            "<img class='action-but' title='删除此行' onclick='delTableRow(this)' src='" . root . "img/control/list_del.svg'>" .
            hidden(array('name' => 'mxId[]', 'value' => $id)),
            $operator,
            $subjectSelect,
            $assist,
            $rule,
            $calculate,
            $val
        ];
        $json['html']  = $this->tableMany(array('tr' => $tr, 'thead' => false));
        return json_encode($json, 320);
    }

    public function getAssit()
    {
        $vouvherObj   = new voucherEditClass();
        $subject      = query('subject', "id = '" . $this->post('subjectId') . "'");
        $json['html'] = '';
        if ($subject['id']) {
            $assistAccountIds = explode(',', $subject['assistAccountIds']);
            $subjectName      = $subject['code'] . ' ' . subjectClass::getName($subject['id']);
            $itemHtml         = '';
            foreach ($assistAccountIds as $val) {
                switch ($val) {
                    case '客户':
                        $khid     = $this->post('khid');
                        $kehu     = query('kehu', "khid = '$khid'");
                        $text     = text(array('name' => 'clientId', 'data' => ['code' => $kehu['orderNo'], 'id' => $kehu['khid']], 'value' => clientProfileClass::getName($kehu['khid'], false, ' '), 'other' => "data-type='khid'", 'class' => 'assit-part', 'title' => '请选择'));
                        $itemHtml .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;

                        break;
                    case '供应商':
                        $supplierId = $this->post('supplierId');
                        $supplier   = query('supplier', "id = '$supplierId'");
                        $text       = text(array('name' => 'supplierId', 'data' => ['code' => $supplier['code'], 'id' => $supplier['id']], 'value' => supplierClass::getName($supplier['id'], false, ' '), 'other' => "data-type='supplierId'", 'class' => 'assit-part', 'title' => '请选择'));
                        $itemHtml   .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                        break;
                    case '员工':
                        $staffId  = $this->post('staffId');
                        $info     = query('staff', "stid = '$staffId'");
                        $text     = text(array('name' => 'staffId', 'data' => ['code' => $info['orderNo'], 'id' => $info['stid']], 'value' => implode(' ', array_filter([$info['orderNo'], $info['name']])), 'other' => "data-type='staffId'", 'class' => 'assit-part', 'title' => '请选择'));
                        $itemHtml .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                        break;
                    case '部门':
                        $departmentId = $this->post('departmentId');
                        $info         = query('department', "id = '$departmentId'");
                        $text         = text(array('name' => 'departmentId', 'data' => ['code' => $info['orderNo'], 'id' => $info['id']], 'value' => implode(' ', array_filter([$info['orderNo'], $info['name']])), 'other' => "data-type='departmentId'", 'class' => 'assit-part', 'title' => '请选择'));
                        $itemHtml     .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                        break;
                    case '项目':
                        $projectId = $this->post('projectId');
                        $info      = query('project', "id = '$projectId'");
                        $text      = text(array('name' => 'projectId', 'data' => ['code' => $info['orderNo'], 'id' => $info['id']], 'value' => implode(' ', array_filter([$info['orderNo'], $info['name']])), 'other' => "data-type='projectId'", 'class' => 'assit-part', 'title' => '请选择'));
                        $itemHtml  .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                        break;
                    case '存货':
                        $materialId = $this->post('materialId');
                        $material   = query('material', "id = '$materialId'");
                        $text       = text(array(
                            'name'  => 'materialId',
                            'data'  => ['code' => $material['code'], 'id' => $material['id']],
                            'value' => implode('-', array_filter([$material['code'], $material['name']])),
                            'other' => "data-type='materialId'",
                            'class' => 'assit-part width300',
                            'title' => '请选择'
                        ));
                        $itemHtml   .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                        break;
                    case '现金流':
                        $cashId   = $this->post('cashId');
                        $info     = query('cash', "id = '$cashId'");
                        $text     = text(array('name' => 'cashId', 'data' => ['code' => $info['code'], 'id' => $info['id']], 'value' => implode(' ', array_filter([$info['code'], $info['name']])), 'other' => "data-type='cashId'", 'class' => 'assit-part', 'title' => '请选择'));
                        $itemHtml .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                        break;
                    default:
                        break;
                }

            }
            $isCurrency = '否';
            if ($subject['numAccount'] == '是' || $subject['currencyAccount'] == '是') {
                $isCurrency = '是';
            }
            if($itemHtml) {
                $json['html'] = <<<eof
<div class="auxiliary-accounting">
    $itemHtml
    <div class="auxiliary-accounting-button">
        <input type="button" value="取消" onclick="hideAssist()">
        <input type="button" value="确定" onclick="confirmAssistTransfer('{$this->post('id')}','$subject[id]','$isCurrency','$subjectName')" class="confirm-button">
    </div>
    {$vouvherObj->assitJs()}
</div>
eof;
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 配置保存
     */
    public function settingSave()
    {
        $id = $this->post('id') ?: self::getId();

        $mxIds      = $this->post('mxId')?:[];
        $directions = $this->post('direction');
        $subjectIds = $this->post('subjectId');
        $summarys   = $this->post('summary');
        $formula   = $this->post('formula');

        $field      = [
            'name'          => $this->post('templateName'),
            'voucherWordId' => $this->post('voucherWordId'),
        ];
        $annotation = [
            'name'          => '模板名称',
            'voucherWordId' => '凭证字',
        ];

        $rules = [
            'name'          => 'required',
            'voucherWordId' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断找平设置是否错误
        $makeLevel = 0;
        foreach ($mxIds as $k => $mxId) {
            $arr = json_decode(base64_decode($formula[$k]),true);
            foreach ((array)$arr as $array){
                if($array['rule'] == '找平'){
                    $makeLevel++;
                }
            }
        }
        if($makeLevel > 1){
            $json['warn'] = '一个模板中只能设置一个找平规则';
            goto resp;
        }

        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => 'salary_setting', 'where' => " and id !='$id' and name = '$field[name]' and coid = '" . self::$coid . "'")) > 0) {
            $json['warn'] = '已存在相同名称的模板';
        } elseif (static::is_null_array($mxIds)) {
            $json['warn'] = '请填写凭证规则';
        } elseif (static::is_null_array($summarys)) {
            $json['warn'] = '请填写摘要';
        } elseif (static::is_null_array($subjectIds)) {
            $json['warn'] = '请选择科目';
        } elseif (static::is_null_array($directions)) {
            $json['warn'] = '请选择方向';
        } else {
            $this->startTrans();
            $where                = " id = '$id' ";
            $voucherWord          = query('voucher_word', "id = '$field[voucherWordId]'");
            $field['voucherWord'] = $voucherWord['word'];
            $info                 = query(self::table, $where);
            if (!$info['id']) {
                $field        = array_merge($field, [
                    'id'    => $id,
                    'coid'  => self::$coid,
                    'isDel' => 1
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            foreach ($mxIds as $k => $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                $arr = json_decode(base64_decode($formula[$k]),true);
                $rule = '';
                foreach ((array)$arr as $array){
                    if($array['rule'] == '找平'){
                        $rule = '自动找平';
                    }
                }
                if (empty($mx['id'])) {
                    $warn = static::insert(array(
                        'table' => self::tableMx,
                        'field' => [
                            'id'        => $mxId,
                            'coid'      => self::$coid,
                            'orderId'   => $id,
                            'subjectId' => $subjectIds[$k],
                            'summary'   => $summarys[$k],
                            'direction' => $directions[$k],
                            'rule' => $rule,
                            'formula' => base64_decode($formula[$k]),
                        ]
                    ));
                } else {
                    $warn = static::update(array(
                        'table' => self::tableMx,
                        'field' => [
                            'subjectId' => $subjectIds[$k],
                            'direction' => $directions[$k],
                            'rule' => $rule,
                            'summary'   => $summarys[$k],
                            'formula' => base64_decode($formula[$k]),
                        ],
                        'where' => "id = '$mxId'"
                    ));
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => "orderId = '$id' and id not in ('" . implode("','", $mxIds) . "')"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);

    }

    /**
     *  测算金额
     */
    public function calculateAamount()
    {
        $month      = $this->post('month');
        $preMonth   = date('Y-m', strtotime("-1 month", strtotime($month . '-01')));
        $ids        = implode("','", $this->post('listId'));
        $multObj    = new multiColumnAccountClass();
        $balanceObj = new subjectBalanceClass();
        $profitObj  = new profitQuarterlyClass();
        $voucherObj = new voucherEditClass();
        $data       = [];
        //测算系统模板的结转金额
        $all = find(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "' and id in ('$ids') order by list asc"));
        foreach ($all['array'] as $period_end_setting) {
            switch ($period_end_setting['name']) {
                case "计提工资":
                    /*$totalMoney=0;
                    $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' and direction = '贷' order by list"]);
                    foreach ($period_end_setting_all['array'] as $array) {
                        $columns = [];
                        $multObj->loopSubjectIds($array['subjectId'], $columns);
                        foreach ($columns as $subjectId) {
                            $subject    = query('subject', "id = '$subjectId'");
                            $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                            $totalMoney += $balance;
                        }
                    }*/
                    $totalMoney = $voucherObj->calculateMoney('', '应付职工薪酬', $month);
                    $html       = "<li>{$totalMoney}" . componentClass::tipComponent("本期计提工资及社保公积金合计：{$totalMoney}元", allowHTML: true) . "</li>";
                    $data[]     = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                case "计提折旧":
                    $totalMoney = 0;
                    if ($period_end_setting['para'] == '有固定资产记录') {
                        // 对应会计期间的资产折旧明细的当月折旧
                        $endDate = $month . '-' . sprintf('%02d', date('t', strtotime($month)));
                        $result  = find(array(
                            "table" => "asset_depreciation_detail as detail join asset_depreciation as asset on detail.orderId = asset.id",
                            'field' => "detail.*",
                            "where" => "asset.coid = '" . self::$coid . "' and asset.month = '$month' and asset.state = '已通过' order by detail.list"
                        ));
                        foreach ($result['array'] as $array) {
                            $asset = query('asset', " id = '{$array['atid']}' ");
                            $ratio      = assetManagementClass::monthRatio($asset['depreciationMethod'], $asset['discountYear'], $asset['money'], $asset['purchaseMoney'], $asset['depreciationMoney'], $asset['purchaseDate'], $endDate, 1);
                            $totalMoney += assetManagementClass::monthDecMoney($asset['depreciationMethod'], $asset['purchaseMoney'], $ratio / 100, $asset['purchaseDate'], $endDate, $asset['discountYear'], $asset['money'], $asset['depreciationMoney']);
                        }
                    } else {
                        // 资产卡片折旧科目当月余额
                        $period_end_setting_all = find(['table' => 'asset_reg', 'where' => "state = '已确认' and disSubjectId <> '' order by time"]);
                        foreach ($period_end_setting_all['array'] as $array) {
                            $columns = [];
                            $multObj->loopSubjectIds($array['disSubjectId'], $columns);
                            foreach ($columns as $subjectId) {
                                $subject    = query('subject', "id = '$subjectId'");
                                $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                                $totalMoney += $balance;
                            }
                        }
                    }
                    $html   = "<li>{$totalMoney}" . componentClass::tipComponent("本月累计折旧：{$totalMoney}", allowHTML: true) . "</li>";
                    $data[] = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                case "摊销无形资产":
                    $totalMoney             = 0;
                    $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' and rule <> '自动找平' order by list"]);
                    foreach ($period_end_setting_all['array'] as $array) {
                        $columns = [];
                        $multObj->loopSubjectIds($array['subjectId'], $columns);
                        foreach ($columns as $subjectId) {
                            $subject      = query('subject', "id = '$subjectId'");
                            $monthBalance = $balanceObj->monthBalance($preMonth, $preMonth, $subject['id']);
                            $totalMoney   += $monthBalance['daiMoney'];
                        }
                    }
                    $html   = "<li>{$totalMoney}" . componentClass::tipComponent("上月累计摊销：{$totalMoney}", allowHTML: true) . "</li>";
                    $data[] = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                case "摊销待摊费用":
                    $totalMoney             = 0;
                    $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' and rule <> '自动找平' order by list"]);
                    foreach ($period_end_setting_all['array'] as $array) {
                        $columns = [];
                        $multObj->loopSubjectIds($array['subjectId'], $columns);
                        foreach ($columns as $subjectId) {
                            $subject      = query('subject', "id = '$subjectId'");
                            $monthBalance = $balanceObj->monthBalance($preMonth, $preMonth, $subject['id']);
                            $totalMoney   += $monthBalance['daiMoney'];
                        }
                    }
                    $html   = "<li>{$totalMoney}" . componentClass::tipComponent("长期待摊费用：{$totalMoney}", allowHTML: true) . "</li>";
                    $data[] = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                case "结转未交增值税":
                    $totalMoney = 0;
                    // 未交
                    $unpaidSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221002'");
                    $columns       = [];
                    $multObj->loopSubjectIds($unpaidSubject['id'], $columns);
                    foreach ($columns as $subjectId) {
                        $subject    = query('subject', "id = '$subjectId'");
                        $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                        $totalMoney += $balance;
                    }
                    $tip = "<p>本期应缴增值税贷方余额：{$totalMoney}</p>";
                    // 预交
                    $advanceSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221018'");
                    $columns        = [];
                    $multObj->loopSubjectIds($advanceSubject['id'], $columns);
                    foreach ($columns as $subjectId) {
                        $subject    = query('subject', "id = '$subjectId'");
                        $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                        $totalMoney += $balance;
                    }
                    $tip    .= "<p>本期预交增值税借方余额：{$totalMoney}</p>";
                    $html   = "<li>{$totalMoney}" . componentClass::tipComponent($tip, allowHTML: true) . "</li>";
                    $data[] = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                case "计提税金":
                    $totalMoney = 0;
                    // 应交
                    $payableSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221001'");
                    $columns        = [];
                    $multObj->loopSubjectIds($payableSubject['id'], $columns);
                    foreach ($columns as $subjectId) {
                        $subject    = query('subject', "id = '$subjectId'");
                        $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                        $totalMoney += $balance;
                    }
                    // 未交
                    $unpaidSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221002'");
                    $columns       = [];
                    $multObj->loopSubjectIds($unpaidSubject['id'], $columns);
                    foreach ($columns as $subjectId) {
                        $subject    = query('subject', "id = '$subjectId'");
                        $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                        $totalMoney += $balance;

                    }
                    // (应交+未交)*借方比率
                    $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' and direction = '借' order by list"]);
                    $rate                   = 0;
                    foreach ($period_end_setting_all['array'] as $array) {
                        $rate += floatval($array['rule']);
                    }
                    $totalMoney = round($totalMoney * ($rate / 100), 2);
                    $html       = "<li>{$totalMoney}</li>";
                    $data[]     = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                case "地方水利基金":
                case "工会经费":
                    $totalMoney             = 0;
                    $period_end_setting_all = find(['table' => 'period_end_setting_detail', 'where' => "orderId = '$period_end_setting[id]' and rule <> '自动找平' order by list"]);
                    foreach ($period_end_setting_all['array'] as $array) {
                        $columns = [];
                        $multObj->loopSubjectIds($array['subjectId'], $columns);
                        foreach ($columns as $subjectId) {
                            $subject    = query('subject', "id = '$subjectId'");
                            $balance    = $this->balanceOnlyMoney($month, $subject['id']);
                            $totalMoney += $balance;
                        }
                    }
                    $html   = "<li>{$totalMoney}</li>";
                    $data[] = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                    break;
                case "计提所得税":
                    $startMonth = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 1);
                    $endMonth   = date('Y', strtotime($month . '-01')) . '-' . sprintf('%02d', (ceil(date('n', strtotime($month . '-01')) / 3) - 1) * 3 + 3);
                    $profit     = $profitObj->totalProfit('利润总额', $startMonth, $endMonth);
                    $profit     = $profit['balance'];
                    $p          = "1.本年累计利润总额(利润表利润总额)：" . $profit;
                    $p          .= "2.应纳税所得额 = 利润总额 - 弥补以前年度亏损= {$profit} - 0.00 = " . $profit;
                    // 应交所得税科目
                    $taxPayableSubject = query('subject', "coid = '" . self::$coid . "' and code = '2221006'");
                    $columns           = [];
                    $multObj->loopSubjectIds($taxPayableSubject['id'], $columns);
                    $daiMoney = $totalMoney = 0;
                    foreach ($columns as $subjectId) {
                        $subject = query('subject', "id = '$subjectId'");
                        //应交所得税科目贷方发生额
                        $monthBalance = $balanceObj->monthBalance($month, $month, $subject['id']);
                        $daiMoney     += $monthBalance['daiMoney'];
                        // 应交所得税期初累计发生额
                        $balance    = $this->balanceOnlyMoney($preMonth, $subject['id']);
                        $totalMoney += $balance;
                    }
                    // 已提金额
                    $amount = $daiMoney + $totalMoney;
                    $p      .= "3.已计提金额 = 应交所得税科目贷方发生额（对方科目为所得税费用）+ 应交所得税期初累计发生额 = " . $amount;
                    if ($profit > 300 * 10000) {
                        $taxation = 100;
                        $taxRate  = 25;
                        $p        .= "4.计提金额计算规则：300万元 < 应纳税所得额，计提金额 = 应纳税所得额 * 100%（计税比例）* 25%（税率）- 已计提金额（计算结果大于0时计提，否则为0不计提）";
                    } elseif ($profit > 100 * 10000 && $profit <= 300 * 10000) {
                        $taxation = 25;
                        $taxRate  = 20;
                        $p        .= "4.计提金额计算规则：100万元 < 应纳税所得额 <= 300万元，计提金额 = 应纳税所得额 * 25%（计税比例）* 20%（税率）- 已计提金额（计算结果大于0时计提，否则为0不计提）";
                    } else {
                        $taxation = 25;
                        $taxRate  = 10;
                        $p        .= "4.计提金额计算规则：0 < 应纳税所得额 <= 100万元，计提金额 = 应纳税所得额 * 25%（计税比例）* 10%（税率）- 已计提金额（计算结果大于0时计提，否则为0不计提）";

                    }
                    $money  = round($profit * ($taxation / 100) * ($taxRate / 100) - $amount, 2);
                    $p      .= "5.计提金额：" . $money;
                    //$html   = "<li>{$money}" . componentClass::tipComponent($p, allowHTML: true) . "</li>";
                    $html   = "<li>{$money}" .  componentClass::promptSvg($p) . "</li>";
                    $data[] = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                case "结转汇兑损益":
                    // 查询本期存在外币的凭证，计算损益差额
                    $result = find(array(
                        "table" => "voucher_detail as detail join voucher as vou on detail.orderId = vou.id",
                        'field' => "detail.*",
                        "where" => "vou.coid = '" . self::$coid . "' and date_format(vou.recordDate,'%Y-%m') = '$month' and vou.workFlow <> '已作废' and detail.currencyId <> '' order by detail.list"
                    ));
                    $money  = 0;
                    foreach ($result['array'] as $array) {
                        $currency  = query("currency", " id = '" . $array['currencyId'] . "' ");
                        $seedMoney = round($array['money'] / $array['rate']);
                        $money     += $array['money'] - round($seedMoney * $currency['rate']);
                    }
                    $money  = self::centToYuan($money);
                    $html   = "<li>{$money}</li>";
                    $data[] = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
                case "结转本期损益":
                    $income = $cost = 0;
                    //查询损益类本期余额合计
                    $subject_all = find(['table' => 'subject', 'where' => "coid = '" . self::$coid . "' and type = '损益类' order by list"]);
                    foreach ($subject_all['array'] as $array) {
                        $columns = [];
                        $multObj->loopSubjectIds($array['id'], $columns);
                        foreach ($columns as $subjectId) {
                            $subject = query('subject', "id = '$subjectId'");
                            $balance = $this->balanceOnlyMoney($month, $subject['id']);
                            if ($subject['direction'] == '贷') {
                                $income += $balance;
                            } else {
                                $cost += $balance;
                            }
                        }
                    }
                    $p      = "<p>1.本期收入合计：{$income}</p><p>2.本期成本费用合计：{$cost}</p>";
                    $money  = $income - $cost;
                    $html   = "<li>{$money}" . componentClass::tipComponent($p, allowHTML: true) . "</li>";
                    $data[] = ['id' => $period_end_setting['id'], 'html' => $html];
                    break;
            }
        }
        $json['warn'] = 2;
        $json['data'] = $data;
        return json_encode($json, 320);
    }

    /**
     * 计算转入的余额
     */
    public function calculateBalance($id, $month)
    {
        $rule = companyClass::returnRule(1);
        if ($rule == 'enterpriseRule') {
            $subjectCode = '4103';
        } else {
            $subjectCode = '3103';
        }
        $info    = query('period_end_setting', "id = '$id'");
        $multObj = new multiColumnAccountClass();
        $all     = find(array('table' => 'period_end_setting_detail', 'where' => "orderId = '$id' order by list asc"));
        $money   = 0;
        foreach ($all['array'] as $array) {
            $columns = [];
            $multObj->loopSubjectIds($array['subjectId'], $columns);
            foreach ($columns as $subjectId) {
                //获取与科目余额方向相反的
                $subject = query('subject', "id = '$subjectId'");
                if ($subject['code'] != $subjectCode) {
                    $balance = $this->balanceOnlyMoney($month, $subject['id']);
                    if ($info['type'] == '结转损益（费用）' && $subject['direction'] == '借') {
                        $money += $balance;
                    } elseif ($info['type'] == '结转损益（收入）' && $subject['direction'] == '贷') {
                        $money += $balance;
                    }
                }
            }
        }
        return $money;
    }

    /**
     * 判断是否已结转损益
     */
    public function juageIsEndProfitAndLoss($month): bool
    {
        //判断损益类的科目余额是否为0
        $bool = $this->checkBalance($month, '损益类');
        if (!$bool) {
            return false;
        }
        return true;
    }

    /**
     * 检查成本归集与结转
     */
    private function checkCostTrans($month): bool
    {
        $subjectObj = new subjectBalanceClass();
        $multObj    = new multiColumnAccountClass();
        $all        = find(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "' and type in ('结转销售产品成本','结转制造费用','结转完工产品成本')"));
        foreach ($all['array'] as $array) {
            $childRes = find(array('table' => 'period_end_setting_detail', 'where' => "orderId = '$array[id]' and direction = '贷' order by list asc"));
            foreach ($childRes['array'] as $item) {
                //判断最后一级科目余额是否为0
                $columns = [];
                $multObj->loopSubjectIds($item['subjectId'], $columns);
                foreach ($columns as $subjectId) {
                    $balanceResult = $subjectObj->balance($month, $subjectId);
                    if ($balanceResult['balance'] != 0) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * “现金净增加额”=资产负债表中“货币资金”期末金额－期初金额
     * @param $month
     * @return bool
     */
    private function checkCash($month)
    {
        $preMonth       = date('Y-m', strtotime("-1 month", strtotime($month . '-01')));
        $assetDebt      = new assetDebtClass();
        $assetResult    = $assetDebt->balance('货币资金', $month);
        $assetPreResult = $assetDebt->balance('货币资金', $preMonth);
        $cashFlow       = new cashFlowClass();
        $all            = find(array('table' => 'cash', 'field' => "distinct type", 'where' => "coid = '" . self::$coid . "' and type != '' order by any_value(code)"));
        $monthBalance   = 0;
        foreach ($all['array'] as $index => $array) {
            $children = find(array('table' => 'cash', 'where' => "coid = '" . self::$coid . "' and type = '$array[type]' order by code"));
            foreach ($children['array'] as $item) {
                $result       = $cashFlow->balance($month, $item['id']);
                $monthBalance += $result['monthBalance'];
            }
        }
        if (round($monthBalance, 2) == round($assetResult['balance'] - $assetPreResult['balance'], 2)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 期末“未分配利润”=利润表中“净利润”+资产负债表中“未分配利润”的年初数
     */
    private function checkProfit($month): bool
    {
        $assetDebt   = new assetDebtClass();
        $result      = $assetDebt->balance('未分配利润', $month);
        $proft       = new profitIncomeClass();
        $proftResult = $proft->totalProfit('净利润', $month, companyClass::returnRule(1));
        if (round($result['balance'], 2) == round($proftResult['balance'] + $result['preBalance'], 2)) {
            return true;
        } else {
            return false;
        }
    }


    private function checkisRecord($month): bool
    {
        if (self::total(['table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and workFlow !='已记账'"]) > 0) {
            return false;
        }
        return true;
    }

    /**
     * 成本类或损益类科目是否有余额
     */
    private function checkBalance($month, $type)
    {
        $subjectObj = new subjectBalanceClass();
        $all        = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and type = '$type' and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->checkBalanceMx($array['id'], $month, $subjectObj);
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 成本类或损益类科目是否有余额
     */
    private function checkBalanceMx($pid, $month, $subjectObj)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balanceResult = $subjectObj->balance($month, $pid);
            if ($balanceResult['balance'] != 0) {
                return false;
            }
        }
        foreach ($all['array'] as $array) {
            $bool = $this->checkBalanceMx($array['id'], $month, $subjectObj);
            if (!$bool) {
                return $bool;
            }
        }
        return true;
    }

    /**
     * 资产负债是否平衡
     * @param $month
     * @return bool
     */
    public function checkAsset($month): bool
    {
        $assetDebt = new assetDebtClass();
        $res       = $assetDebt->content($month);
        if (round($res['assetMoney'], 2) != round($res['debtMoney'], 2)) {
            return false;
        } elseif (round($res['assetInitMoney'], 2) != round($res['debtInitMoney'], 2)) {
            return false;
        }
        return true;
    }

    /**
     *
     */
    private function voucherCert($type, $month): bool
    {
        $template = query('period_end_setting', "coid = '" . self::$coid . "' and type = '$type'");
        if (static::total(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and isTemplate = '否' and sourceId = '$template[id]' and date_format(recordDate,'%Y-%m') = '$month'")) > 0) {
            return true;
        }
        return false;
    }

    /**
     *存货、原材料和库存商品是否存在红数
     */
    private function checkMaterialNum($month): bool
    {
        $subjectObj = new subjectBalanceClass();
        $all        = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('1403','1405') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            if ($array['numAccount'] == '是') {
                $bool = $this->checkMaterialNumMx($array['id'], $month, $subjectObj);
                if (!$bool) {
                    return false;
                }
            }
        }
        return true;
    }

    private function checkMaterialNumMx($pid, $month, $subjectObj)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balanceResult = $subjectObj->balance($month, $pid);
            if ($balanceResult['num'] < 0) {
                return false;
            }
        }
        foreach ($all['array'] as $array) {
            $bool = $this->checkMaterialNumMx($array['id'], $month, $subjectObj);
            if (!$bool) {
                return $bool;
            }
        }
        return true;
    }

    /**
     * 检查主营业务收入和主营业务成本数量核算是否有不一致
     */
    private function checkMainbusiness($month): bool
    {
        $subjectObj = new subjectBalanceClass();
        $subject    = query('subject', "coid = '" . self::$coid . "' and code ='5001' and state = '启用'");
        $recNum     = $this->childMainbuiness($subject['id'], $month, $subjectObj);
        $subject    = query('subject', "coid = '" . self::$coid . "' and code = '5401' and state = '启用'");
        $payNum     = $this->childMainbuiness($subject['id'], $month, $subjectObj);
        if ($recNum != $payNum) {
            return false;
        }

        return true;
    }

    /**
     *
     * @param $pid
     * @param $month
     * @param $subjectObj
     * @return float
     */
    private function childMainbuiness($pid, $month, $subjectObj)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balanceResult = $subjectObj->balance($month, $pid);
            return $balanceResult['num'];
        }
        $num = 0;
        foreach ($all['array'] as $array) {
            $num += $this->childMainbuiness($array['id'], $month, $subjectObj);
        }
        return $num;
    }


    /**
     * 判断凭证号是否连续
     */
    private function checkDiscontinuous($month): bool
    {
        $all = find(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and isTemplate = '否' order by any_value(voucherNo) asc", 'field' => "distinct voucherWordId"));
        foreach ($all['array'] as $array) {
            //取最大的凭证号
            $first   = query('voucher', "coid = '" . self::$coid . "' and isTemplate = '否' and voucherWordId = '$array[voucherWordId]' and date_format(recordDate,'%Y-%m') = '$month'  order by voucherNo asc");
            $firstNo = $first['voucherNo'] ?: 1;
            $max     = query('voucher', "coid = '" . self::$coid . "' and isTemplate = '否' and voucherWordId = '$array[voucherWordId]' and date_format(recordDate,'%Y-%m') = '$month'  order by voucherNo desc");
            $maxNo   = $max['voucherNo'];
            for ($i = $firstNo; $i <= $maxNo; $i++) {
                if (static::total(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and isTemplate = '否' and voucherWordId = '$array[voucherWordId]' and date_format(recordDate,'%Y-%m') = '$month' and voucherNo = '$i'")) == 0) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 检查应收账款是否存在贷方余额
     */
    private function shouldRec($month)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('1122') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, '贷');
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查应付账款是否存在借方余额
     */
    private function shouldPay($month)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('2202') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, '借');
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查原材料、库存商品有数量为零，金额不为0的情况
     * @param $month
     * @return bool
     */
    private function checkMaterial($month)
    {
        $subjectObj = new subjectBalanceClass();
        $all        = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('1403','1405') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            if ($array['numAccount'] == '是') {
                $bool = $this->checkNum($array['id'], $month, $subjectObj);
                if (!$bool) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 判断库存商品，原材料数量为零，金额不为0
     * @param $pid
     * @param $month
     * @param $subjectObj
     * @return bool|null
     */
    private function checkNum($pid, $month, $subjectObj)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balanceResult = $subjectObj->balance($month, $pid);
            if (($balanceResult['balance'] == 0 && $balanceResult['num'] != 0) || ($balanceResult['balance'] != 0 && $balanceResult['num'] == 0)) {
                return false;
            }
        }
        foreach ($all['array'] as $array) {
            $bool = $this->checkNum($array['id'], $month, $subjectObj);
            if (!$bool) {
                return $bool;
            }
        }
        return true;
    }

    /**
     * 检查短期、长期借款是否有借方余额
     * @param $month
     * @return bool
     */
    private function checkShortOrLongMoney($month)
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('2001','2501') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, '借');
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 现金、银行存款存在贷方余额检查
     * @param $month
     * @return bool
     */
    private function checkCashAndBank($month): bool
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and code in ('1001','1002') and state = '启用' order by list asc"));
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, '贷');
            if (!$bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * @param $pid
     * @param $month
     * @param $direction
     * @return bool|null
     */
    private function findBlance($pid, $month, $direction): ?bool
    {
        $all = find(array('table' => 'subject', "where" => "coid = '" . self::$coid . "' and pid = '$pid' and state = '启用' order by list asc"));
        if (is_array($all['array']) && count($all['array']) == 0) {
            $balance = $this->balanceOnlyMoney($month, $pid);
            if ($direction == '借' && $balance > 0) {
                //判断是否有借方余额
                return false;
            } elseif ($direction == '贷' && $balance < 0) {
                //判断是否有贷方余额
                return false;
            }
            return true;
        }
        foreach ($all['array'] as $array) {
            $bool = $this->findBlance($array['id'], $month, $direction);
            if (!$bool) {
                return $bool;
            }
        }
        return true;
    }

    public function balanceOnlyMoney($month, $subjectId)
    {
        $subject = query('subject', "id = '$subjectId'");
        if (empty($subject['id'])) {
            return 0;
        }
        //期初金额
        $initMoney = $subject['initMoney'] ?: 0;
        $jieInit   = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') <= '$month'" . voucherClass::joinWhere()));
        $daiInit   = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') <= '$month'" . voucherClass::joinWhere()));
        if ($subject['direction'] == '借') {
            $jieInit['money'] += $initMoney;
        } else {
            $daiInit['money'] += $initMoney;
        }
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($subject['direction'] == '借') {
            return round($jieInit['money'] - $daiInit['money'], 2);
        } else {
            return round($daiInit['money'] - $jieInit['money'], 2);
        }
    }

    private function settingStyle(): string
    {
        return <<<eof
<style>
.check-block{padding-left: 20px}
.check-block>ul>li>img{width: 20px;height: 20px;vertical-align: text-top;}
.check-block>ul>li>span{margin-left: 5px}
.stage-three-block{margin-top: 10px}
.stage-three-block ul li{padding: 5px}
.setting-content{padding: 10px;margin-top: 10px;max-height: 650px;overflow-y: auto;}
.progress-li-line{width: 200px;border-top: 1px solid #629AFD;margin-top: 20px}
.now-li{background-color: #629AFD;color: white !important;}
.progress-li{width: 40px;height: 40px;border: 1px solid #629AFD;line-height: 40px;text-align: center;border-radius: 50%;color: #629AFD}
.progress-text{position: absolute;white-space: nowrap;margin-top: 5px}
.progress-content{display: flex;flex-direction: row;padding: 20px}
.tag-list-ul>li{float: left;padding: 5px;margin: 5px}
.tag-contain{width: 258px;height: 130px;padding: 10px;border: 1px solid #d7d7d7;border-radius: 2px;position: relative;overflow: hidden}
.tag-contain .set-ico{cursor: pointer;}
.tag-contain-add{text-align: center;color: #e6e6e6;display: flex;flex-direction: column;justify-content: center;cursor: pointer;border-style: dashed}
.tag-contain-add .tag-contain-add-sign{font-weight: bold;font-size: 60px;height: 45px}
.tag-contain-add .tag-contain-add-title{font-size: 30px;}
.tag-contain-title-text{margin-left: 10px;font-weight: bold;font-size: 14px}
.tag-contain-body{padding: 10px;}
.tag-contain-ul li{padding: 5px 20px 0 20px;font-size: 16px;font-weight: bold;display: flex;align-items: center;}
.tag-contain-foot{padding: 10px;border-bottom: 1px solid #d7d7d7}
.tag-edit-content{display: flex;justify-content: space-between;padding: 10px 0;}
.label-edit-ul li{float: left}
.add-attr-button{border: 2px solid #6aacfb;margin-top: 5px;color: #6aacfb;font-weight: bold;font-size: 21px; width: 16px;height: 16px;text-align: center;line-height: 13px;cursor: pointer;border-radius: 2px;}
.disable-button{background-color: #e6e6e6;}
.tableMany td {border: 1px solid #e6e6e6!important;font-size: 14px;}
.tab-button {display: flex;align-items: center;flex-wrap: nowrap;}
.checkbox [disabled] {background-color: #cdcdcd;}
</style>
eof;

    }

    /**
     * 样式
     */
    private function style(): string
    {
        return <<<eof
<style>
.dot{display: inline-block;width: 20px;height: 20px;border-radius: 50%;vertical-align: text-bottom;}

.to-left{margin-left: 50px}
.period-content{padding: 10px 0;overflow: auto;height: calc(100vh - 80px);}
.year-font{font-weight: 700;font-size: 20px}
.period-content-year{padding: 10px 0}
.row-item-ul{display: flex;flex-direction: row;justify-content: flex-start;margin-top: 10px;cursor: pointer}
.row-item-ul .row-item{width: 100px;height: 90px;border: 1px solid rgba(98, 154, 253, 1);border-radius: 4px;margin-right: 15px}
.row-item-top{height: 28px;background-color: rgba(98, 154, 253, 1)}
.row-item-bottom{text-align: center;line-height: 60px;font-weight:700}
.yellow{background-color: #F59A23}
.yellow-border{border-color: #F59A23 !important;}
.gray{background-color: #D7D7D7}
.gray-border{border-color: #D7D7D7 !important;}
.blue{background-color: #629AFD}
.blue-border{border-color: #629AFD !important;}
</style>
eof;

    }


    // 操作中转
    public function operate()
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = "是否确认删除此期末结转自定义模板？";
                $function = 'delete';
                $form     = self::page . 'OperateForm, terminalTransferForm';
                $power    = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (!$info['isDel']) {
                    //返回
                    $warn = "删除失败：系统预设模板不能删除\n";
                } elseif (static::total(array('table' => 'voucher', 'where' => "sourceId = '$id'")) > 0) {
                    $warn = "删除失败：此模板已被使用\n";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 是否已结转损益
     * @param $month
     * @return bool
     */
    public static function isChecked($month): bool
    {
        //获取最新结账日期
        $period_end    = query('period_end_setting', "coid = '".self::$coid."' and name = '结转本期损益'");
        if (static::total(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and sourceId = '".$period_end['id']."'")) > 0) {
            return true;
        } else {
            return false;
        }
    }

}
